package com.tool.mylibrary.permission;

import android.content.Context;
import android.content.DialogInterface;

import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RequestExecutor;
import com.yanzhenjie.permission.Setting;

import java.util.List;

/**
 * 再次封装下andPermission的工具类
 * Created by Google on 2018/5/27.
 */
/*
使用示例，用的时候直接复制，根据实际情况，修改 requestPermission里面的权限
 public void initPermisson() {
        PermissionUtils permissionUtils = new PermissionUtils(MainActivity.this);
        //传入申请的是权限还是权限组，可以是单个权限/权限组 或者多个权限/权限组
        //permissionUtils.requestPermission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE);
        permissionUtils.setOnPermissionResult(new PermissionUtils.OnPermissionResult() {
            @Override
            public void onRequestSuccess() {//申请成功
                Toast.makeText(MainActivity.this, "申请权限成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSettingBack() {//从设置回来
                Toast.makeText(MainActivity.this, "从设置回来", Toast.LENGTH_SHORT).show();
            }
        });
        permissionUtils.requestPermission(Permission.Group.CAMERA, Permission.Group.STORAGE,
                Permission.Group.LOCATION);
    }
 */
public class PermissionUtils {

    Context mContext;

    public PermissionUtils(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * 申请单个或者多个权限，直接用就行，
     * @param permissions  一个或多个权限参数
     */
    public void requestPermission(String... permissions) {

        if (AndPermission.hasPermissions(mContext, permissions)) {
            if (onPermissionResult != null) {
                onPermissionResult.onRequestSuccess();
            }
        } else {
            AndPermission.with(mContext)
                    .runtime()
                    .permission(permissions)
                    .rationale(new DefaultRationale())
                    .onGranted(new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> data) {
                            if (onPermissionResult != null) {
                                onPermissionResult.onRequestSuccess();
                            }
                        }
                    }).onDenied(new Action<List<String>>() {
                @Override
                public void onAction(List<String> permissions) {

                    if (AndPermission.hasAlwaysDeniedPermission(mContext, permissions)) {
                        List<String> permissionNames = Permission.transformText(mContext, permissions);
                        String message = getMessage(permissionNames, "我们需要以下权限，请在设置中为我们开启：");
                        showDialog(message);
                    }
                }
            }).start();
        }
    }

    /**
     * 申请单个或多个权限组---比如 Permission.Group.STORAGE
     * @param permissions  一个或者多个权限组 参数
     */
    public void requestPermission(String[]... permissions) {
        if (AndPermission.hasPermissions(mContext, permissions)) {
            if (onPermissionResult != null) {
                onPermissionResult.onRequestSuccess();
            }
        } else {
            AndPermission.with(mContext)
                    .runtime()
                    .permission(permissions)
                    .rationale(new DefaultRationale())
                    .onGranted(new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> data) {
                            if (onPermissionResult != null) {
                                onPermissionResult.onRequestSuccess();
                            }
                        }
                    }).onDenied(new Action<List<String>>() {
                @Override
                public void onAction(List<String> permissions) {

                    if (AndPermission.hasAlwaysDeniedPermission(mContext, permissions)) {
                        List<String> permissionNames = Permission.transformText(mContext, permissions);
                        String message = getMessage(permissionNames, "我们需要以下权限，请在设置中为我们开启：");
                        showDialog(message);
                    }
                }
            }).start();
        }
    }


    /**
     * 弹出让用户设置的对话框
     * @param message
     */
    private void showDialog(String message) {
        AlertDialog.newBuilder(mContext)
                .setCancelable(false)
                .setTitle("提示")
                .setMessage(message)
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AndPermission.with(mContext)
                                .runtime()
                                .setting()
                                .onComeback(new Setting.Action() {
                                    @Override
                                    public void onAction() {
                                        // 用户从设置回来了。
                                        if (onPermissionResult != null) {
                                            onPermissionResult.onSettingBack();
                                        }
                                    }
                                })
                                .start();

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

    /**
     * 获取提示信息
     * @param permissionNames
     * @param title
     * @return
     */
    private String getMessage(List<String> permissionNames, String title) {
        StringBuilder builder = new StringBuilder();
        builder.append(title);
        for (String s : permissionNames) {
            builder.append(s);
            builder.append("\n");
        }
        return builder.toString();
    }

    OnPermissionResult onPermissionResult;

    public interface OnPermissionResult {
        void onRequestSuccess();

        void onSettingBack();//从设置回来
    }

    public void setOnPermissionResult(OnPermissionResult onPermissionResult) {
        this.onPermissionResult = onPermissionResult;
    }

    public final class DefaultRationale implements Rationale<List<String>> {

        @Override
        public void showRationale(Context context, List<String> permissions, final RequestExecutor executor) {
            List<String> permissionNames = Permission.transformText(context, permissions);
            String message = getMessage(permissionNames, "允许以下权限以便程序继续执行：");
//            String message = context.getString(R.string.message_permission_rationale, TextUtils.join("\n", permissionNames));

            AlertDialog.newBuilder(context)
                    .setCancelable(false)
                    .setTitle("提示")
                    .setMessage(message)
                    .setPositiveButton("继续", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            executor.execute();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            executor.cancel();
                        }
                    })
                    .show();
        }
    }
}
